package com.boyinet.imesh2json.viewmodel

import com.boyinet.imesh2json.bean.Type
import com.boyinet.imesh2json.model.ProductTypeModel
import com.boyinet.imesh2json.repo.TypeRepository
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class ProductTypesViewModel {

    @Autowired
    lateinit var typeRepository: TypeRepository

    var current: ProductTypeModel = ProductTypeModel()

    var index: Int = -1

    var update: Boolean = false

    val typeList: ObservableList<Type> by lazy {
        FXCollections.observableArrayList(typeRepository.findTypesByTypeEquals(0))
    }

    val unitList: ObservableList<Type> by lazy {
        FXCollections.observableArrayList(typeRepository.findTypesByTypeEquals(1))
    }

    fun delete(type: Type) {
        when (type.type) {
            0 -> typeList.remove(type)
            1 -> unitList.remove(type)
        }
        typeRepository.delete(type)
    }

    fun update() {
        val type: Type = current.export()
        when (type.type) {
            0 -> typeList[index] = type
            1 -> unitList[index] = type
        }
        typeRepository.save(type)
    }

    fun insert() {
        val type: Type = current.export()
        when (type.type) {
            0 -> typeList.add(type)
            1 -> unitList.add(type)
        }
        typeRepository.save(type)
    }

}